package net.huashitong.wxpay;

import jodd.http.HttpBrowser;
import jodd.http.HttpRequest;
import net.huashitong.ssydt.security.utils.MD5;
import net.huashitong.ssydt.security.utils.Sha1Util;
import net.huashitong.util.XMLUtil;
import org.jdom2.JDOMException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author shaoxian.zhong
 * @create 2018-06-28 17:10
 */
public class RequestHandler {
    /** 统一下单url地址 */
    private String unifiedorderUrl;
    /** Token */
    private String Token;
    /** 商户参数 */
    private String appid;
    private String appkey;
    private String partner;
    private String notifyUrl;

    /**
     * 初始构造函数。
     *
     * @return
     */
    public RequestHandler(HttpServletRequest request,
                          HttpServletResponse response) {
        this.Token = "token_";

        unifiedorderUrl = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    }
    /**
     * 初始化函数。
     */
    public void init(String app_id, String app_key, String partner, String notifyUrl) {
        this.appkey = app_key;
        this.appid = app_id;
        this.partner = partner;
        this.notifyUrl = notifyUrl;
    }

    public void init() {

    }

    /**
     * 公众号支付
     * @param body
     * @param out_trade_no
     * @param spbill_create_ip
     * @param total_fee
     * @param nonceStr
     * @param openid
     * @return
     */
    public String WeChatgenProductArgs(String body,
                                       String out_trade_no,
                                       String spbill_create_ip,
                                       String total_fee,
                                       String nonceStr,
                                       String openid) {
        try {
            SortedMap<String,String> packageParams = new TreeMap<String, String>();
            packageParams.put("appid", this.appid);
            packageParams.put("body", body);
            packageParams.put("mch_id", this.partner);
            packageParams.put("nonce_str", Sha1Util.getNonceStr());
            packageParams.put("notify_url", this.notifyUrl);
            packageParams.put("out_trade_no", out_trade_no);
            packageParams.put("spbill_create_ip", spbill_create_ip);
            packageParams.put("total_fee", total_fee);
            packageParams.put("trade_type", "JSAPI");
            packageParams.put("openid", openid);

            String sign = genPackageSign(packageParams);
            packageParams.put("sign", sign);

            String xmlstring =toXml(packageParams);
            return xmlstring;

        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 生成签名
     * @author: huiyang.yu
     * @param params
     * @return
     */
    public String genPackageSign(SortedMap<String, String> params) {
        StringBuilder sb = new StringBuilder();

        Set es = params.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()){
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();

            sb.append(k);
            sb.append('=');
            sb.append(v);
            sb.append('&');
        }
        sb.append("key=");
        sb.append(this.appkey);


        String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        System.out.println("packageSign="+packageSign);
        return packageSign;
    }

    /**
     * 生成XML
     * @author: huiyang.yu
     * @param params
     * @return
     */
    private String toXml(SortedMap<String, String> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        Set es = params.entrySet();
        Iterator it = es.iterator();
        while(it.hasNext()){
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();

            if ("body".equalsIgnoreCase(k)) {
                sb.append("<"+k+">");
                sb.append("<![CDATA[");
                sb.append(v);
                sb.append("]]>");
                sb.append("</"+k+">");
            } else {
                sb.append("<"+k+">");
                sb.append(v);
                sb.append("</"+k+">");
            }
        }

        sb.append("</xml>");

        return sb.toString();
    }

    /**
     * 发起统一下单请求
     * @author: huiyang.yu
     * @param entity
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public Map<String, String> unifiedorder(String entity) {
        HttpBrowser browser = new HttpBrowser();
        HttpRequest httpRequest = HttpRequest.post(unifiedorderUrl);
        httpRequest.header("Content-Type", "text/xml");
        try {
            httpRequest.body(new String(entity.getBytes(), "iso-8859-1"));
        } catch (Exception E) {

        }
        browser.sendRequest(httpRequest);
        Map<String, String> map = null;
        try {
            String resContent = browser.getPage();
            resContent = new String(resContent.getBytes("iso-8859-1"), "utf-8");
            System.out.println("\r\n---接收的XML---\r\n"+resContent+"\r\n---接收的XML---\r\n");
            map = XMLUtil.doXMLParse(resContent );
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;

    }
    /**
     * 生成公众号支付统一下单的XML字符串
     * @author: huiyang.yu
     * @param body
     * @param out_trade_no
     * @param spbill_create_ip
     * @param total_fee
     * @param nonceStr
     * @return
     */
    public String WebgenProductArgs(String body,
                                    String out_trade_no,
                                    String spbill_create_ip,
                                    String total_fee,
                                    String nonceStr) {

        try {
            SortedMap<String,String> packageParams = new TreeMap<String, String>();
            packageParams.put("appid", this.appid);
            packageParams.put("body", body);
            packageParams.put("mch_id", this.partner);
            packageParams.put("nonce_str",nonceStr);
            packageParams.put("notify_url", this.notifyUrl);
            packageParams.put("out_trade_no", out_trade_no);
            packageParams.put("spbill_create_ip", spbill_create_ip);
            packageParams.put("total_fee", total_fee);
            packageParams.put("trade_type", "NATIVE");

            String sign = genPackageSign(packageParams);
            packageParams.put("sign", sign);


            String xmlstring =toXml(packageParams);
            return xmlstring;

        } catch (Exception e) {
            return null;
        }
    }
}
